//
//  DistributionViewController.m
//  PrintPort
//
//  Created by 华谕 on 2017/11/14.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "DistributionViewController.h"
#import "MemberModel.h"

static NSString *cellPath = @"DistributionCell";
@interface DistributionViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UILabel *firstMemLab;
    UILabel *secondMemLab;
    UILabel *allMoneyLab;
}
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSMutableArray *distriFirstAry;
@property (nonatomic, strong)NSMutableArray *distriSecondAry;
@property (nonatomic, assign)NSInteger distriType;
@property (nonatomic, assign)NSInteger leftPage;
@property (nonatomic, assign)NSInteger rightPage;
@property (nonatomic, strong)NSString *praentID;

@end

@implementation DistributionViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _distriType = 0;
    _leftPage = 0;
    _rightPage = 0;
    _praentID = @"";
    _distriFirstAry = [NSMutableArray arrayWithCapacity:0];
    _distriSecondAry = [NSMutableArray arrayWithCapacity:0];
    [self creatUI];
    [self requestDistriList:@"" Page:_leftPage];
    [self requestMyDistrion];
}

- (void)creatUI
{
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"我的分销";
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60*displaywidth)];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    NSArray *titAry = @[@"一级成员\n20",@"二级成员\n40",@"返利总金\n￥160"];
    CGFloat W = (SCREEN_WIDTH-2*displaywidth)/3;
    for (int i = 0; i < 3; i++)
    {
        UILabel *label = [ZCControl createLabelWithFrame:CGRectMake(i*(W + 1*displaywidth), 5*displaywidth, W, 50*displaywidth) Font:14.0 Text:titAry[i] Color:RGB(77, 77, 77)];
        label.textAlignment = NSTextAlignmentCenter;
        [topView addSubview:label];
        if (i != 2)
        {
            UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(W+(W+1*displaywidth)*i, 0, 1*displaywidth, 60*displaywidth)];
            lineview.backgroundColor = LinesColor;
            [topView addSubview:lineview];
        }
        if (i == 0)
        {
            firstMemLab = label;
        }
        else if (i == 1)
        {
            secondMemLab = label;
        }
        else
        {
            allMoneyLab = label;
        }
    }
    CGFloat heightX = 0;
    if (SCREEN_HEIGHT == 812)
    {
        heightX = 34;
    }
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 60*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-60*displaywidth-heightX) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.backgroundColor = BacksColor;
    [self.view addSubview:_tableview];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.tableview.mj_footer.automaticallyHidden = YES;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    
}

- (void)loadNewHeaderData
{
    if (_distriType == 0)
    {
        _leftPage = 0;
        [self requestDistriList:@"" Page:_leftPage];

    }
    else
    {
        _rightPage = 0;
        [self requestDistriList:_praentID Page:_rightPage];
    }
    
}

- (void)loadMoreFootData
{
    if (_distriType == 0)
    {
        _leftPage++;
        [self requestDistriList:@"" Page:_leftPage];

    }
    else
    {
        _rightPage++;
        [self requestDistriList:_praentID Page:_rightPage];

    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_distriType == 0)
    {
        return _distriFirstAry.count;
    }
    return _distriSecondAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1*displaywidth)];
    lineview.backgroundColor = LinesColor;
    [cell.contentView addSubview:lineview];
    if (_distriType == 0)
    {
        if (_distriFirstAry.count > 0)
        {
            MemberModel *model = _distriFirstAry[indexPath.row];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 10*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"face"];
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            imgView.layer.cornerRadius = 20*displaywidth;
            imgView.layer.masksToBounds = YES;
            if (model.imgUrl.length > 0)
            {
                [imgView sd_setImageWithURL:[NSURL URLWithString:model.imgUrl] placeholderImage:[UIImage imageNamed:@"face"]];
            }
            [cell.contentView addSubview:imgView];
            UILabel *namelab = [ZCControl createLabelWithFrame:CGRectMake(65*displaywidth, 5*displaywidth, 120*displaywidth, 25*displaywidth) Font:14.0 Text:model.nickname Color:RGB(77, 77, 77)];
            [cell.contentView addSubview:namelab];
            NSString *phoneStr = model.phone;
            if (phoneStr.length > 9)
            {
                phoneStr = [phoneStr stringByReplacingCharactersInRange:NSMakeRange(3, 5)  withString:@"*****"];
            }
            UILabel *phonelab = [ZCControl createLabelWithFrame:CGRectMake(65*displaywidth, 30*displaywidth, 120*displaywidth, 25*displaywidth) Font:10.0 Text:phoneStr Color:RGB(173, 173, 173)];
            [cell.contentView addSubview:phonelab];
            
            UILabel *titlab = [ZCControl createLabelWithFrame:CGRectMake(175*displaywidth, 20*displaywidth, 45*displaywidth, 20*displaywidth) Font:11.0 Text:@"奖励：" Color:RGB(77, 77, 77)];
            [cell.contentView addSubview:titlab];
            UILabel *moneylab = [ZCControl createLabelWithFrame:CGRectMake(220*displaywidth, 20*displaywidth, 100*displaywidth, 20*displaywidth) Font:11.0 Text:[NSString stringWithFormat:@"￥%@",model.reward] Color:RGB(255, 111, 28)];
            [cell.contentView addSubview:moneylab];
            
        }
    }
    else
    {
        if (_distriSecondAry.count > 0)
        {
            MemberModel *model = _distriSecondAry[indexPath.row];
            UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 10*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"face"];
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            imgView.layer.cornerRadius = 20*displaywidth;
            imgView.layer.masksToBounds = YES;
            if (model.imgUrl.length > 0)
            {
                [imgView sd_setImageWithURL:[NSURL URLWithString:model.imgUrl] placeholderImage:[UIImage imageNamed:@"face"]];
            }
            [cell.contentView addSubview:imgView];
            UILabel *namelab = [ZCControl createLabelWithFrame:CGRectMake(65*displaywidth, 10*displaywidth, 120*displaywidth, 40*displaywidth) Font:14.0 Text:model.nickname Color:RGB(77, 77, 77)];
            [cell.contentView addSubview:namelab];
           
            
            UILabel *titlab = [ZCControl createLabelWithFrame:CGRectMake(175*displaywidth, 20*displaywidth, 45*displaywidth, 20*displaywidth) Font:11.0 Text:@"奖励：" Color:RGB(77, 77, 77)];
            [cell.contentView addSubview:titlab];
            UILabel *moneylab = [ZCControl createLabelWithFrame:CGRectMake(220*displaywidth, 20*displaywidth, 100*displaywidth, 20*displaywidth) Font:11.0 Text:[NSString stringWithFormat:@"￥%@",model.reward] Color:RGB(255, 111, 28)];
            [cell.contentView addSubview:moneylab];
            
            UIButton *backBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-40*displaywidth, 15*displaywidth, 30*displaywidth, 30*displaywidth) ImageName:@"fanhui" Target:self Action:@selector(backAction) Title:nil Font:11.0];
            backBtn.backgroundColor = [UIColor clearColor];
            [cell.contentView addSubview:backBtn];
            
            
            
        }
        
    }
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_distriType == 0)
    {
        MemberModel *model = _distriFirstAry[indexPath.row];
        _distriType = 1;
        _rightPage = 0;
        [self requestDistriList:model.selfCode Page:_rightPage];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60*displaywidth;
}


- (void)backAction
{
    _distriType = 0;
    [self.tableview reloadData];
}


- (void)requestMyDistrion
{
    WEAKSELF;
    [HYBaseHandler requestMyDistrionParmers:nil Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
//            @[@"一级成员\n20",@"二级成员\n40",@"返利总金\n￥160"]
            NSString *firstStr = obj[@"data"][@"firstMemberNum"];
            NSString *secondStr = obj[@"data"][@"secondMemberNum"];
            NSString *moneyStr = obj[@"data"][@"moneyTol"];
            firstStr = [NSString stringWithFormat:@"一级成员\n￥%@",firstStr];
            secondStr = [NSString stringWithFormat:@"二级成员\n￥%@",secondStr];
            moneyStr = [NSString stringWithFormat:@"返利总金\n￥%@",moneyStr];
            dispatch_async(dispatch_get_main_queue(), ^{
                firstMemLab.text = firstStr;
                secondMemLab.text = secondStr;
                allMoneyLab.text = moneyStr;
            });

        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
        
    } failed:^(NSError *error) {
        
    }];
}

- (void)requestDistriList:(NSString *)code Page:(NSInteger)page
{
    WEAKSELF;
    NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%ld",page],
                          @"size":@"10",
                          @"recommendCode":code,
                          @"queryType":[NSString stringWithFormat:@"%ld",_distriType+1]
                          };
    [HYBaseHandler requestDistriListParmers:dic Success:^(id obj)
    {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        if ([obj server_Getcodecheck])
        {
            if ([obj[@"data"] isKindOfClass:[NSString class]])
            {
                return;
            }
            NSArray *memberAry = [MemberModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            if (_distriType == 0)
            {
                if (_leftPage == 0)
                {
                    [weakSelf.distriFirstAry removeAllObjects];
                }
                [weakSelf.distriFirstAry addObjectsFromArray:memberAry];
            }
            else
            {
                if (_rightPage == 0)
                {
                    [weakSelf.distriSecondAry removeAllObjects];
                }
                [weakSelf.distriSecondAry addObjectsFromArray:memberAry];
                if (weakSelf.distriSecondAry.count == 0)
                {
                    [LTools showMBProgressWithText:@"暂无二级成员" addToView:weakSelf.view];
                    _distriType = 0;
                    return;
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview  reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];

        }
    } failed:^(NSError *error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];

    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
